﻿using PLCS.Domain.Shared.Orders;

namespace PLCS.Domain.Orders;

/// <summary>
/// 工单表
/// </summary>
public class Order : BaseEntity
{
    /// <summary>
    /// 编号
    /// </summary>
    public string UpperNo { get; set; }

    /// <summary>
    /// 线体编码
    /// </summary>
    public string PdLineNo { get; set; }

    /// <summary>
    /// 托盘编码
    /// </summary>
    public string? TrayNo { get; set; }

    /// <summary>
    /// 工单号
    /// </summary>
    public string OrderNo { get; init; }

    /// <summary>
    /// 方案编号
    /// </summary>
    public string SolutionNo { get; set; }

    /// <summary>
    /// 工单类型
    /// </summary>
    public OrderType OrderType { get; set; }

    /// <summary>
    /// 上线工位/加工工位（根据工单类型来定）
    /// </summary>
    public string OnlineStation { get; set; }

    /// <summary>
    /// 计划开始时间
    /// </summary>
    public DateTime PlanStartTime { get; set; }

    /// <summary>
    /// 计划结束时间
    /// </summary>
    public DateTime PlanEndTime { get; set; }

    /// <summary>
    /// 实际开始时间
    /// </summary>
    public DateTime? FactStartTime { get; set; }

    /// <summary>
    /// 工单状态
    /// </summary>
    public OrderStatus Status { get; private set; }

    [NotMapped]
    public List<OrderRunningCondition>? OrderRunningConditions { get; set; }

    public Order()
    {
    }

    public Order(string upperNo, string solutionNo, string lineNo, string orderNo, DateTime planStartTime, DateTime planEndTime, OrderType orderType, string onlineStation)
    {
        UpperNo = upperNo;
        PdLineNo = lineNo;
        OrderNo = orderNo;
        PlanStartTime = planStartTime;
        PlanEndTime = planEndTime;
        Status = OrderStatus.未解析;
        OrderType = orderType;
        OnlineStation = onlineStation;
        SolutionNo = solutionNo;
    }

    public Order SetTrayNo(string trayNo)
    {
        TrayNo = trayNo;
        return this;
    }

    public void ChangeStatus(OrderStatus status)
    {
        Status = status;
        if (status == OrderStatus.执行完成)
            AddLocalEvent(new OrderFinshEvent()
            {
                Id = Id,
                SolutionNo = SolutionNo,
                LineNo = PdLineNo,
                FactStartTime = PlanStartTime,
                TrayNo = TrayNo,
                OrderNo = OrderNo,
                PlanStartTime = PlanStartTime,
                OrderType = OrderType,
                PlanEndTime = PlanEndTime,
                OnlineStation = OnlineStation,
                UpperNo = UpperNo
            });
    }
}